package cn.kgc.shiro;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.util.Arrays;
import java.util.List;

/**
 * @author: mosin
 * @version: v1.0  2022/11/16
 * 自定义域对象  完成认证和授权操作
 */
public class MyRealm extends AuthorizingRealm {
    // 授权   角色 权限字符串
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //授权操作
        Object primaryPrincipal = principals.getPrimaryPrincipal();
        // 根据用户名查询用户权限信息    user  role  menu
        System.out.println("用户的授权操作被调用");

        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addRole("admin");
        List<String> roles = Arrays.asList("super", "visitor");
        simpleAuthorizationInfo.addRoles( roles);

        //添加权限字符串授权   * 
        //simpleAuthorizationInfo.addStringPermission("user:delete");
        simpleAuthorizationInfo.addStringPermission("user:*");
        return simpleAuthorizationInfo;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
         // 获取用户身份信息
        String principal = (String) token.getPrincipal();
        // 根据用户名查询数据库    principal   ->user  username password    token  ->  info

        if("admin".equals(principal)) {
            // 将根据用户名查询的数据结果封装成AuthenticationInfo类型的对象返回 用于密码的校验
            // 参数1 用户名  参数2  密码  参数3  salt  参数4 域对象的名字
            SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo("admin", "85c78ccc640dc16561c4785aa5ebd557", ByteSource.Util.bytes("hello"), this.getName());
            return simpleAuthenticationInfo;
        }
        return null;
    }
}
